package com.medical.standard.controller.export;

import com.medical.standard.service.ExportService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/export/report")
public class ReportExportServlet extends HttpServlet {

    private ExportService exportService;

    @Override
    public void init() throws ServletException {
        this.exportService = new ExportService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        try {
            // 获取筛选参数
            String standardCode = request.getParameter("standardCode");
            String projectName = request.getParameter("projectName");

            Map<String, Object> filters = new HashMap<>();
            if (standardCode != null && !standardCode.trim().isEmpty()) {
                filters.put("standardCode", standardCode.trim());
            }
            if (projectName != null && !projectName.trim().isEmpty()) {
                filters.put("projectName", projectName.trim());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = new String("认可检验检测能力表.xlsx".getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 导出表格
            exportService.exportInspectionCapacityTable(response, filters);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"error\": \"导出失败: " + e.getMessage() + "\"}");
        }
    }
}